<style lang="less" scoped>
.permission-list {
  padding: 20px;
  border: 1px solid #3f95ff;
  max-height: 200px;
  overflow: auto;
}
</style>
<template>
  <div class="comp-new">
    <el-form ref="newForm" :model="newForm" :label-width="150 + 'px'">
      <el-form-item
        label="角色名称："
        prop="name"
        :rules="[{ required: true, message: '请输入角色名称' }]"
      >
        <el-input placeholder="请输入" v-model.trim="newForm.name"></el-input>
      </el-form-item>
      <el-form-item label="选择权限：" prop="permissionsId">
        <div class="permission-list">
          <el-tree
            ref="tree"
            node-key="id"
            :props="props"
            :data="permissionList"
            show-checkbox
            :indent="36"
            :default-expanded-keys="defaultExpandedKeys"
            @check-change="handleCheckChange"
          >
          </el-tree>
          <!-- :default-checked-keys="checkedKeys" -->
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { mapState } from "vuex";
export default {
  name: "newRecordAccount",
  props: {
    activeData: {
      type: Object,
      default() {
        return null;
      },
    },
  },
  computed: {
    ...mapState(["scale"]),
  },
  watch: {
    activeData() {
      this.initForm();
    },
  },
  data() {
    return {
      newForm: {},
      loading: false,
      props: {
        label: "name",
        children: "childList",
      },
      permissionList: [],
      checkedKeys: [],
      defaultExpandedKeys: [0],
      TreechildList: [
        {
          id: "002",
          name: "查看",
        },
        {
          id: "003",
          name: "查看",
          flag: false,
        },
        {
          id: "004",
          name: "查看",
          flag: false,
        },
        {
          id: "017",
          name: "查看",
          flag: false,
        },
        {
          id: "018",
          name: "查看",
          flag: false,
        },
        {
          id: "029",
          name: "查看",
          flag: false,
        },
        {
          id: "030",
          name: "查看",
          flag: false,
        },
        {
          id: "001",
          name: "查看",
          flag: false,
        },
        {
          id: "013",
          name: "查看",
          flag: false,
        },
      ],
    };
  },
  created() {
    this.getPermission();
    this.initForm();
  },
  mounted() {
    this.$refs.tree.setCheckedKeys(this.checkedKeys, false);
  },
  methods: {
    getPermission() {
      this.$get("/systemsetup/systemsetup/permissionsTreeList").then((res) => {
        this.permissionList = [
          {
            id: 0,
            level: 0,
            pid: -1,
            name: "全选",
            childList: res.data.childList,
          },
        ];
        this.permissionList[0].childList.forEach((item) => {
          this.TreechildList.forEach((xitem) => {
            if (xitem.id == item.id) {
              item.childList.unshift(xitem);
            }
          });
        });
      });
    },
    handleCheckChange(data) {
      let checkedKeys = this.$refs.tree.getCheckedKeys();
      let halfCheckedKeys = this.$refs.tree.getHalfCheckedKeys();
      // this.newForm.permissionsId = [checkedKeys, halfCheckedKeys].join(",");//before
      let permissionsIdArr = new Set([...checkedKeys, ...halfCheckedKeys]);
      this.newForm.permissionsId = [...permissionsIdArr].join(",");
    },
    getPermissionsId(permissionList) {
      let ids = [];
      permissionList.forEach((item) => {
        if (item.flag) {
          ids.push(item.id);
          this.defaultExpandedKeys.push(item.pid);
          if (!item.childList) {
            this.checkedKeys.push(item.id);
          }
        }
        if (item.childList) {
          let childIds = this.getPermissionsId(item.childList);
          ids = [...ids, ...childIds];
        }
      });
      return ids;
    },
    initForm() {
      if (this.activeData) {
        let { id, name, permissionsList } = this.activeData;
        permissionsList.forEach((item) => {
          this.TreechildList.forEach((xitem) => {
            if (xitem.id == item.id && item.flag) {
              item.childList.unshift(xitem);
              Object.assign(xitem, {
                flag: item.flag,
                level: item.level,
                pid: item.pid,
              });
            }
          });
        });
        this.newForm = { id, name };
        let permissionsId = new Set([
          ...this.getPermissionsId(permissionsList),
        ]);
        this.newForm.permissionsId = [...permissionsId].join(",");
      } else {
        this.newForm = {};
        if (this.$refs["newForm"]) {
          this.$refs["newForm"].resetFields();
        }
      }
    },
    submitAction() {
      if (this.permissionList.length == 0) {
        this.$emit("fail");
        this.$message.error("当前账号无权限");
        return;
      }
      this.$refs["newForm"].validate((valid) => {
        if (valid) {
          this.$emit("submitting");
          let params = Object.assign({}, this.newForm);
          let url = params.id
            ? "/systemsetup/systemsetup/roleUpdate"
            : "/systemsetup/systemsetup/roleAdd";
          this.$post(url, params).then(
            (data) => {
              this.loading = false;
              this.$message.success("保存成功");
              this.$emit("success", data);
            },
            (error) => {
              this.$emit("fail");
              this.$message.error(error.msg);
            }
          );
        } else {
          return false;
        }
      });
    },
    cancelAction() {
      this.$emit("cancel");
    },
  },
};
</script>
